package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;


@Service
@Transactional//开启事务
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired(required = false)
    StringRedisTemplate redisTemplate;

    /**
     * 新增菜品 和对应新增口味
     *
     * @param dto
     * @return
     */
    @Override
    public Result addDish(DishDTO dto) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dto, dish);

        //想菜品插入一条数据
        dishMapper.addDish(dish);

        //获取insert语句生成的主键值,这个值是在mapper层返回的
        // 用<insert id="insert" useGeneratedKeys="true" keyProperty="id">才能返回的
        Long dishId = dish.getId();

        //通过dto获取从前端过来的口味数组
        List<DishFlavor> flavors = dto.getFlavors();
        //判断口味数组是否存在,并通过遍历把每一个dishid补全
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //补全之后开始插入口味数据
            dishFlavorMapper.addDishFlavor(flavors);
        }

        //清理redis缓存
        String pattern = "dish_" + dish.getCategoryId();
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result dishPage(DishPageQueryDTO dishPageQueryDTO) {
        //处理参数,给默认参数
        if (dishPageQueryDTO.getPage() == null) {
            dishPageQueryDTO.setPage(1);
        }
        if (dishPageQueryDTO.getPageSize() == null) {
            dishPageQueryDTO.setPageSize(5);
        }

        //开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //调用dao
        Page<Dish> dishPageList = dishMapper.dishPage(dishPageQueryDTO);

        //获取结果中的菜品集合
        List<Dish> dishList = dishPageList.getResult();

        //3.3声明一个list用来承载vo对象集合
        List<DishVO> dishVoList =new ArrayList(dishList.size());

        //3.2 为每一条数据添加菜品分类名称
        dishList.forEach(dish -> {
            //1.声明一个vo对象
            DishVO vo=new DishVO();
            BeanUtils.copyProperties(dish,vo);
            //2.获取分类名称
            Category category = categoryMapper.getName(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            //3.写入数据到voList
            dishVoList.add(vo);
        });

        //返回数据 需要用到专用pageResult封装分页查询返回数据
        PageResult pageResult = new PageResult();
        //当前返回的list需要用到vo因为Dish没有页面所需要的分类名称数据
        pageResult.setRecords(dishList);
        pageResult.setTotal(dishPageList.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Override
    public Result deleteByIds(List<Long> ids) {
        //查询当前菜品是否在起售状态,是就返回
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //要删除的菜品里有菜品为启用状态直接返回不能删除
                return Result.error(MessageConstant.DISH_ON_SALE);//起售中商品不能删除
            }
        }
        //2.查询当前菜品是否关联套餐,如果关联则不能删除
        List<Long> setmealId = setmealDishMapper.getByDishId(ids);
        if (setmealId != null && setmealId.size() > 0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3如果删除菜品也要把口味一并删除
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishId(ids);

        //清理redis缓存
        String pattern = "dish_*";
        cleanCache(pattern);

        return Result.success();
    }


    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        //判空
        if (id == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }

        //调用dao根据id获取dish
        Dish dish = dishMapper.selectById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(dish.getId());

        //封装到Vo一起返回数据给前端
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);

        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateDish(DishDTO dto) {
        //判空
        if (dto.getId() == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }
        //拷贝数据到dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDish(dish);

        //删除口味关联表
        dishFlavorMapper.deleteByDishId2(Arrays.asList(dish.getId()));
        //新增菜品口味关联表
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }
        //批量插入
        dishFlavorMapper.addDishFlavor(flavors);

        //清理redis缓存
        String pattern = "dish_" + dish.getCategoryId();
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateStatus(Integer status, Long id) {
        if (id == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.updateDish(dish);

        if (status == StatusConstant.DISABLE){
            //如果是停售操作,还需要将包含当前菜品的套餐也停售
            ArrayList<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getByDishId(dishIds);
            if (setmealIds != null && setmealIds.size()>0){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public Result getByCategoryId(Long categoryId) {
        if (categoryId == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId);
        return Result.success(dishList);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //构造redis中的key，规则：dish_分类id
        String key = "dish_" + dish.getCategoryId();
        //查询redis中有没有redis,有则直接返回结果
        String disVoListStr = redisTemplate.opsForValue().get(key);
        //把字符串穿换成list集合
        List<DishVO> dishVOListForRedis = JSONArray.parseArray(disVoListStr, DishVO.class);
        if (dishVOListForRedis != null && dishVOListForRedis.size() != 0){
            return dishVOListForRedis;
        }
        //否则就是没有数据,查询mysql,写入数据到redis中
        //条件查询对应的菜品集合
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //写入数据到redis
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return dishVOList;
    }


    /**
     * 封装的有一个请求缓存的方法
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
